package cn.bs.securitystudy.service.impl;

import cn.bs.securitystudy.mapper.UserMapper;
import cn.bs.securitystudy.pojo.User;
import cn.bs.securitystudy.vo.UserLogin;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.omg.CORBA.Object;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户信息
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        //如果没有查询到用户就抛异常
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }

        //todo 查询用户权限
        List<String> test = Arrays.asList("test","hello","world");
        //把数据封装成UserDetails返回
        return new UserLogin(user,test);
    }
}
